Monkey Documentation

Drawing with Images

In this tutorial we load some images from our apps data folder and learn more about mojo.graphics.

Import mojo
    
Class Game Extends App

    Field image:Image

    Method OnCreate()
        SetUpdateRate 30
        image=LoadImage("monkey64.png")
    End

    Method OnRender()
        Cls
        DrawImage image,20,20       
    End

End

Function Main()
    New Game()
End

Create a new monkey file, paste the above code, and save as "game.monkey" in a new folder on your computer.

This app, when run, produces a black display as the LoadImage command will fail to find the file monkey64.png.

In the same folder that you saved "game.monkey" create a new directory named "game.data". Copy this image to the newly created .data folder.

Add Points where you Click

Now we add a new Point class that contains an x y coordinate pair using floating point values.

Class Point
    Field x#
    Field y#
End

We also add a List container to manage the Points that we store each time the user clicks on the screen.

    Field points:=New List<Point>

The := syntax is a shortcut for a standard equate that infers the type of the Left Hand Side (LHS) from the type on the Right Hand Side (RHS). In this case the Field named points of type List<Point> could have also been declared and initialized using the longer winded:

    Field points:List<Point>=New List<Point>

The type List<Point> is an example of a monkey template. A List<Point> supports the standard List interface but specifically for objects of type Point.

Import mojo

Class Point
    Field x#
    Field y#
End

Class Game Extends App

    Field image:Image
    Field points:=New List<Point>

    Method OnCreate()
        SetUpdateRate 30
        image=LoadImage("monkey64.png")
    End

    Method AddPoint(x#,y#)
        Local p:Point=New Point
        p.x=x
        p.y=y
        points.AddLast p
    End

    Method OnUpdate()
        If MouseHit() AddPoint MouseX,MouseY
    End

    Method OnRender()
        Cls
        For Local point:=Eachin points
            DrawImage image,point.x,point.y
        Next
    End

End

Function Main()
    New Game()
End

The AddLast method is called on the list to add an entry each time the user clicks the mouse.

The OnRender method draws the list of monkeys by using the enumeration

        For Local point:=Eachin points

This allows monkey code to process each element of the list in the order they were added.